import sys,os ,socket
ip_port=('localhost',1234)
BASE_DIR=os.path.dirname(os.path.abspath(__file__))
print(BASE_DIR)
class conntClient(object):
    def __init__(self):
        self.args=sys.argv
        if len(self.args):
            self.port=(self.args[1],int(self.args[2]))
        else:
            self.port(ip_port)
        self.creat_socket()
        self.command_fanout()

    def creat_socket(self):
        try:
            self.sk=socket.socket()
            self.sk.connect(self.port)
            print("connent sucess")
        except Exception as e:
            print("error ",e)

    def command_fanout(self):
        while True:
            cmd =input(">>>>>").split()
            if cmd =="exit()":
                break
            cmd,file =cmd.split()
            if hasattr(self,cmd):
                func=getattr(self,cmd)
                func(cmd,file)
            else:
                print("调用失败")

    def put(self,cmd,file):
        if os.path.isfile(file):
            fileName=os.path.basename(file)
            fileSize =os.path.getsize(file)
            fileinfo="%s|%s|%s"%(cmd,fileName,fileSize)
            self.sk.send(bytes(fileinfo,encoding="utf-8"))
            recvStatus=self.sk.recv(1024)
            print("recvStatus",recvStatus)
            hasSend=0
            if str(recvStatus,encoding="utf-8")=="ok":
                with open(file,'rb')as f:
                    while fileSize > hasSend:
                        contant = f.readline(1024)
                        recv_size = len(contant)
                        self.sk.send(contant)
                        hasSend += recv_size
                        s = str(int(hasSend/fileSize*100))+"%"
                        print("文件正在上传" +fileName+"已上传"+s)
                    print("文件上传完毕"% (fileName))
            else:
                print("文件不存在")

    def get(self,cmd,filename):
        path=os.path.join(BASE_DIR,'download',filename)
        if not os.path.isfile(filename):
            fileName =os.path.basename(filename)
            fileinfo ="%s|s%" %(cmd,fileName,0)
            self.sk.sendall(fileinfo,encode="utf-8")
            recv_data = self.sk.recv(1024)  # 接收server发送过来的文件名、文件大小
            print("recv_data", recv_data)
            hasrecv = 0
            filename, fileSize = str(recv_data, encoding="utf-8").split("|")
            self.recv.dict = {self.sk: {"filename": filename, "filesize": int(fileSize)}}  # 接受的文件信息
            if str(self.recv.dict[self.sk][filename], encoding="utf-8") == fileName:
                # 比较文件 名字相同 则开始下载
                with open(path, 'rb')as f:
                    while fileSize > hasrecv:
                        recv_Data = self.sk.recv(1024)
                        contant = f.write(recv_Data)
                        recv_size = len(contant)
                        hasrecv += recv_size
                        s = str(int(hasrecv / fileSize * 100)) + "%"
                        print("文件正在下载" + fileName + "下载完成" + s)
                    print("文件下载完毕" % fileName)
        else:
            print("文件已存在、无需下载")

if __name__ == '__main__':
    conntClient()
    # os.path.basename(__file__)
    # print(os.path.basename(__file__))
